<template>
  <div>
    <a-drawer
      :title="title"
      :closable="false"
      :maskClosable="false"
      :width="800"
      :visible="visible"
      :confirmLoading="confirmLoading">
      <a-spin :spinning="confirmLoading">
        <a-form :form="form">
          <a-row :gutter="24">
            <a-col :md="12" :sm="24">
              <a-form-item label="学院" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  :disabled="readOnly || this.collList.length === 1"
                  show-search
                  allowClear
                  placeholder="请选择学院"
                  v-decorator="['collegeId', { rules: [{ required: true, message: '请选择学院！' }] }]"
                  @change="changeCollege">
                  <a-select-option v-for="item of this.collList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="开课课程" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课课程"
                  v-decorator="['courseId', { rules: [{ required: true, message: '请选择开课课程！' }] }]"
                  :disabled="readOnly || !this.form.getFieldValue('collegeId')">
                  <a-select-option v-for="item of courseList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="开课学年" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  @change="changeSchoolYear"
                  :disabled="readOnly"
                  show-search
                  allowClear
                  placeholder="请选择开课学年"
                  v-decorator="['schoolYearId', { rules: [{ required: true, message: '请选择开课学年！' }] }]">
                  <a-select-option v-for="item of this.schoolYearList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="开课学期" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-select
                  :disabled="readOnly"
                  show-search
                  allowClear
                  placeholder="请选择开课学期"
                  v-decorator="['termId', { rules: [{ required: true, message: '请选择开课学期！' }] }]">
                  <a-select-option v-for="item of this.schoolTermList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <a-form-item label="选课起止时间" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <a-date-picker
                  show-time
                  :disabledDate="disabledDate"
                  :disabled="viewOnly || (record && record.confirmState === 4)"
                  v-decorator="['selectionStartDate']"
                />
                <span>&nbsp;~&nbsp;</span>
                <a-date-picker
                  show-time
                  :disabledDate="disabledDate"
                  :disabled="viewOnly || (record && record.confirmState === 4)"
                  v-decorator="['selectionEndDate']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <a-form-item label="开放学生" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-button
                  type="primary"
                  @click="setStudentChoosenShow"
                  :disabled="viewOnly || (record && record.confirmState === 4) || this.form.getFieldValue('collegeId') === undefined"
                >学生列表({{ selectedStudentList.length }})
                </a-button
                >
                <a-upload :customRequest="uploadStudentList" :multiple="false" :showUploadList="false" name="file">
                  <a-button
                    :disabled="viewOnly ||(record && record.confirmState === 4) || this.form.getFieldValue('collegeId') === undefined">
                    批量导入
                  </a-button>
                </a-upload>

                <a-button @click="exportTemplate">下载导入模板</a-button>
              </a-form-item>
            </a-col>
          </a-row>

          <x-down ref="batchExport" style="display: none"/>

          <a-button type="primary" @click="addTab" style="margin-bottom: 10px" :disabled="readOnly">添加轮次</a-button>
          <a-tabs v-model="currentIndex" type="editable-card" hide-add @edit="onTabsEdit">
            <a-tab-pane
              v-for="(item, index) in frequencyList"
              :key="index"
              :tab="`${index + 1}轮`"
              :closable="!readOnly">
              <a-row :gutter="24">
                <a-col :md="12" :sm="24">
                  <a-form-item label="开课周次" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                    <a-select
                      allowClear
                      placeholder="请选择"
                      v-model="item.weekStart"
                      :disabled="readOnly"
                      @change="item.weekEnd = null">
                      <a-select-option v-for="item1 of frequencyArray" :key="item1">{{ item1 }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="12" :sm="24">
                  <a-form-item label="到" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                    <a-select
                      allowClear
                      placeholder="请选择"
                      v-model="item.weekEnd"
                      :disabled="readOnly || item.weekStart == null">
                      <a-select-option
                        v-for="(item2) of (
                          readOnly || item.weekStart == null ? frequencyArray : frequencyArray.filter((d) => d >= item.weekStart)
                        )"
                        :key="item2">
                        {{ item2 }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :md="24" :sm="24">
                  <a-form-item label="开课日期" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                    <a-checkbox-group v-model="item.days" :options="weekDays" :disabled="readOnly"/>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
        </a-form>
      </a-spin>
      <div class="drawer-footer">
        <a-button class="left" @click="handleCancel">关闭</a-button>
        <a-button class="right" type="primary" @click="handleSubmit" :disabled="viewOnly">提交</a-button>
      </div>
    </a-drawer>

    <a-modal v-model="showStudentChoosen" width="800px" title="学生列表" @ok="chooseStudentOK">
      <a-transfer
        :data-source="allStudentList"
        show-search
        :list-style="{
          width: '352px',
          height: '400px',
        }"
        :titles="['未选择学生列表', '已选择学生列表']"
        :render="(item) => `${item.title}-${item.description}`"
        :filter-option="
          (inputValue, option) => option.title.indexOf(inputValue) > -1 || option.description.indexOf(inputValue) > -1
        "
        :target-keys="selectedStudentList"
        @change="handleChange"/>
    </a-modal>
  </div>
</template>

<script>
  import moment from 'moment'
  import { XDown } from '@/components'
  import {
    coursePublishAdd,
    coursePublishEdit,
    exportStudentCollectionTemplate,
    uploadStudentList
  } from '@/api/modular/main/coursePublishManage'
  import { coursePublishFrequencyList } from '@/api/modular/main/coursePublishFrequencyManage'
  import { coursePublishStudentList } from '@/api/modular/main/coursePublishStudentManage'
  import { sysCollegeList } from '@/api/modular/system/sysCollegeManage'
  import { sysSchoolYearList } from '@/api/modular/system/sysSchoolYearManage'
  import { sysSchoolTermList } from '@/api/modular/system/sysSchoolTermManage'
  import { courseList } from '@/api/modular/system/courseManage'
  import { getUserByType } from '@/api/modular/system/userManage'

  export const dateFormat = 'YYYY-MM-DD HH:mm:ss'

  export default {
    components: {
      XDown
    },
    data() {
      return {
        currentIndex: 0,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        visible: false,
        confirmLoading: false,
        viewOnly: false, // 只读
        record: undefined,
        form: this.$form.createForm(this),
        id: '',
        title: '',
        courseList: [],
        collList: [],
        schoolYearList: [],
        schoolTermList: [],
        showStudentChoosen: false,
        allStudentList: [],
        selectedStudentList: [],
        frequencyArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], // 开课周次,
        defaultTimeRange: [], // using by datePicker component
        weekDays: [
          { label: '周一', value: 1 },
          { label: '周二', value: 2 },
          { label: '周三', value: 3 },
          { label: '周四', value: 4 },
          { label: '周五', value: 5 }
        ],
        frequencyList: [
          // {
          //   id: undefined,
          //   index: 1,
          //   weekStart: null,
          //   weekEnd: null,
          //   days: []
          // }
        ]
      }
    },
    computed: {
      readOnly() {
        if (this.viewOnly) return true
        // 如果是新建状态，可修改
        if (this.record === undefined) return false
        // 如果不是新建状态 并且 发布状态是已发布，只读
        return this.record.publishState === 1
      }
    },
    methods: {
      disabledDate(current) {
        return current && current < moment().subtract(1, 'days').endOf('day')
      },
      getCoursePublishFrequencyList() {
        coursePublishFrequencyList({
          coursePublishId: this.id
        }).then((res) => {
          if (res.success) {
            this.frequencyList = res.data.map((item, index) => {
              return {
                id: item.id,
                index: index + 1,
                weekStart: item.weekStart,
                weekEnd: item.weekEnd,
                days: item.dayOfWeek.split(',').map((item) => parseInt(item))
              }
            })
          }
        })
      },
      getCoursePublishStudentList() {
        coursePublishStudentList({
          coursePublishId: this.id
        }).then((res) => {
          this.selectedStudentList = res.data.map((item) => item.studentId)
        })
      },
      getStudentList() {
        const collegeId = this.form.getFieldValue('collegeId')
        getUserByType({
          userType: 'stu',
          collId: collegeId
        }).then((res) => {
          if (res.success) {
            this.allStudentList = res.data.map((item) => {
              return {
                key: item.id,
                title: item.userNum,
                description: item.name
              }
            })
          }
        })
      },
      /**
       * load学院列表
       */
      getCollList() {
        sysCollegeList().then((res) => {
          if (res.success) {
            this.collList = res.data
            if (this.collList.length === 1) {
              const collegeId = this.collList[0].id
              this.form.setFieldsValue({
                collegeId: collegeId
              })
              this.getCourseList(collegeId)
            }
          }
        })
      },
      /**
       * load学年列表
       */
      getSchoolYearList() {
        sysSchoolYearList().then((res) => {
          if (res.success) {
            this.schoolYearList = res.data
          }
        })
      },
      /**
       * load开课学期
       */
      getSchoolTermList(schoolYearId) {
        sysSchoolTermList({
          schoolYearId: schoolYearId
        }).then((res) => {
          if (res.success) {
            this.schoolTermList = res.data
          }
        })
      },
      /**
       * load课程
       */
      getCourseList(collegeId) {
        courseList({
          collId: collegeId
        }).then((res) => {
          if (res.success) {
            this.courseList = res.data
          }
        })
      },
      changeCollege(collegeId) {
        this.getCourseList(collegeId)
        this.form.setFieldsValue({
          courseId: undefined
        })
        this.selectedStudentList = []
      },
      handleChange(targetKeys, direction, moveKeys) {
        // console.log(targetKeys)
        // console.log(direction)
        // console.log(moveKeys)
        this.selectedStudentList = targetKeys
      },
      setStudentChoosenShow() {
        this.getStudentList()
        this.showStudentChoosen = true
      },
      chooseStudentOK() {
        this.showStudentChoosen = false
      },
      addTab() {
        const currentIndex = this.frequencyList.length
        this.frequencyList.push({
          id: undefined,
          weekStart: null,
          weekEnd: null,
          days: []
        })
        this.currentIndex = currentIndex
      },
      onTabsEdit(targetKey, action) {
        if (action === 'add') {
          // do nothing.
        } else if (action === 'remove') {
          this.frequencyList.splice(targetKey, 1)
          this.currentIndex = this.frequencyList.length - 1
        }
      },
      // 初始化方法
      open(record, viewOnly) {
        this.getCollList()
        this.getSchoolYearList()
        this.getSchoolTermList()
        if (record) {
          this.viewOnly = viewOnly
          this.title = viewOnly ? '查看开课课程' : '编辑开课课程'
          this.record = record
          // test only , removable
          // this.record.publishState = 1
          // this.record.confirmState = 4
          this.id = record.id
          setTimeout(() => {
            this.form.setFieldsValue({
              id: record.id,
              collegeId: record.collegeId,
              courseId: record.courseId,
              schoolYearId: record.schoolYearId,
              termId: record.termId,
              selectionStartDate: record.selectionStartDate ? moment(record.selectionStartDate, dateFormat) : null,
              selectionEndDate: record.selectionEndDate ? moment(record.selectionEndDate, dateFormat) : null
            })
            this.getCoursePublishFrequencyList()
            this.getCoursePublishStudentList()
            this.getCourseList(record.collegeId)
          }, 100)
        } else {
          this.id = ''
          this.title = '新增开课课程'
        }
        this.visible = true
      },
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          console.log(values)
          if (!errors) {
            // check parameters here.
            // if (this.selectedStudentList.length === 0) {
            //   this.confirmLoading = false
            //   this.$message.error('开放学生不能为空')
            //   return
            // }
            //
            // for (let i = 0; i < this.frequencyList.length; i++) {
            //   const item = this.frequencyList[i]
            //   if (item.weekStart == null || item.weekEnd == null) {
            //     this.confirmLoading = false
            //     this.$message.error(`第${i + 1}轮，开课周次不能为空`)
            //     return
            //   }
            //   if (item.days.length === 0) {
            //     this.confirmLoading = false
            //     this.$message.error(`第${i + 1}轮，开课日期不能为空`)
            //     return
            //   }
            // }

            const _frequencyList = this.frequencyList.filter(item => item.weekStart && item.weekEnd && item.days)
              .map((item, index) => {
                return {
                  id: item.id,
                  frequencyIndex: index + 1,
                  weekStart: item.weekStart,
                  weekEnd: item.weekEnd,
                  dayOfWeek: item.days.join(',')
                }
              })
            const _studentList = this.selectedStudentList.map((item) => {
              return {
                studentId: item
              }
            })

            const data = { ...values }
            // set the time range
            if (data.selectionStartDate && data.selectionEndDate) {
              const selectionStartDate = moment(data.selectionStartDate)
              const selectionEndDate = moment(data.selectionEndDate)
              if (selectionEndDate < selectionStartDate) {
                this.$message.error('选课结束时间不能小于开始时间')
                this.confirmLoading = false
                return
              }
            }
            data.selectionStartDate = data.selectionStartDate ? moment(data.selectionStartDate).format(dateFormat) : null
            data.selectionEndDate = data.selectionEndDate ? moment(data.selectionEndDate).format(dateFormat) : null
            // set the frequency list
            data.frequencyList = _frequencyList
            // set the student list
            data.studentList = _studentList
            if (this.id) {
              data.id = this.id
              coursePublishEdit(data)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('更新开课课程成功')
                    this.confirmLoading = false
                    this.$emit('ok', data)
                    this.handleCancel()
                  } else {
                    this.$message.error('更新开课课程失败：' + res.message)
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            } else {
              coursePublishAdd(data)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('新增开课课程成功')
                    this.confirmLoading = false
                    this.$emit('ok', data)
                    this.handleCancel()
                  } else {
                    this.$message.error('新增开课课程失败：' + res.message)
                  }
                })
                .finally((res) => {
                  this.confirmLoading = false
                })
            }
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel() {
        this.currentIndex = 0
        this.form.resetFields()
        this.selectedStudentList = []
        this.selectedTimeRange = []
        this.frequencyList = []
        this.record = undefined
        this.viewOnly = false
        this.visible = false
      },
      /**
       * 导出采集模板
       */
      exportTemplate() {
        exportStudentCollectionTemplate().then((res) => {
          this.$refs.batchExport.downloadfile(res)
        })
      },
      uploadStudentList(data) {
        const file = data.file
        const fileSize = file.size
        const fileType = file.name.substr(file.name.lastIndexOf('.'))
        console.log('fileType=', fileType)
        if (fileType !== '.xls' && fileType !== '.xlsx') {
          this.$message.error('请上传Excel文件')
          return
        }
        if (fileSize / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50M')
          return
        }
        const formData = new FormData()
        formData.append('collegeId', this.form.getFieldValue('collegeId'))
        formData.append('file', file)
        uploadStudentList(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            const mergedArr = [...this.selectedStudentList, ...res.data]
            this.selectedStudentList = [...new Set(mergedArr)]
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      },
      changeSchoolYear(schoolYearId) {
        this.form.setFieldsValue({
          'termId': undefined
        })
        this.getSchoolTermList(schoolYearId)
      }
    }
  }
</script>
